import os
from PIL import Image, ImageDraw, ImageFont
import sys
import django

# 添加项目路径
sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')
django.setup()

from apps.flowers.models import Flower, FlowerImage

def create_flower_image(flower_name, color_scheme, output_path):
    """创建美观的鲜花图片"""
    width, height = 400, 400
    img = Image.new('RGB', (width, height), color='white')
    draw = ImageDraw.Draw(img)
    
    # 背景渐变效果
    for y in range(height):
        ratio = y / height
        r = int(color_scheme['bg'][0] * (1 - ratio) + color_scheme['bg_end'][0] * ratio)
        g = int(color_scheme['bg'][1] * (1 - ratio) + color_scheme['bg_end'][1] * ratio)
        b = int(color_scheme['bg'][2] * (1 - ratio) + color_scheme['bg_end'][2] * ratio)
        draw.line([(0, y), (width, y)], fill=(r, g, b))
    
    # 绘制花朵
    center_x, center_y = width // 2, height // 2
    
    if '玫瑰' in flower_name:
        # 绘制玫瑰花
        # 花瓣层次
        for i in range(5, 0, -1):
            radius = 30 + i * 15
            for angle in range(0, 360, 45):
                x = center_x + radius * 0.7
                y = center_y + radius * 0.7
                draw.ellipse([x-20, y-15, x+20, y+15], 
                           fill=color_scheme['petals'], outline=color_scheme['outline'])
        
        # 花心
        draw.ellipse([center_x-15, center_y-15, center_x+15, center_y+15], 
                    fill=color_scheme['center'])
                    
    elif '康乃馨' in flower_name:
        # 绘制康乃馨
        # 锯齿状花瓣
        for i in range(8):
            angle = i * 45
            x1 = center_x + 40 * (i % 2 + 1)
            y1 = center_y + 30 * (i % 2 + 1)
            draw.polygon([(center_x, center_y), (x1, y1), (x1+10, y1-20), (center_x+5, center_y-5)], 
                        fill=color_scheme['petals'], outline=color_scheme['outline'])
                        
    elif '百合' in flower_name:
        # 绘制百合花
        # 六片花瓣
        for i in range(6):
            angle = i * 60
            x1 = center_x + 60
            y1 = center_y
            x2 = center_x + 30
            y2 = center_y - 80
            x3 = center_x - 30
            y3 = center_y - 40
            draw.polygon([(center_x, center_y), (x1, y1), (x2, y2), (x3, y3)], 
                        fill=color_scheme['petals'], outline=color_scheme['outline'])
                        
    elif '向日葵' in flower_name:
        # 绘制向日葵
        # 花瓣
        for i in range(16):
            angle = i * 22.5
            x1 = center_x + 80
            y1 = center_y + 10
            x2 = center_x + 60
            y2 = center_y - 10
            draw.polygon([(center_x, center_y), (x1, y1), (x2, y2)], 
                        fill=color_scheme['petals'], outline=color_scheme['outline'])
        
        # 花心
        draw.ellipse([center_x-30, center_y-30, center_x+30, center_y+30], 
                    fill=color_scheme['center'])
                    
    elif '郁金香' in flower_name:
        # 绘制郁金香
        # 花杯形状
        draw.ellipse([center_x-40, center_y-60, center_x+40, center_y+20], 
                    fill=color_scheme['petals'], outline=color_scheme['outline'])
        # 花茎
        draw.rectangle([center_x-5, center_y+20, center_x+5, center_y+100], 
                      fill=(34, 139, 34))
                      
    elif '满天星' in flower_name:
        # 绘制满天星
        # 小花朵散布
        import random
        random.seed(42)  # 固定种子保证一致性
        for _ in range(30):
            x = random.randint(50, width-50)
            y = random.randint(50, height-50)
            size = random.randint(3, 8)
            draw.ellipse([x-size, y-size, x+size, y+size], 
                        fill=color_scheme['petals'], outline=color_scheme['outline'])
    
    # 添加装饰元素
    # 叶子
    for i in range(3):
        x = center_x + (i-1) * 60
        y = center_y + 80
        draw.ellipse([x-15, y-5, x+15, y+25], fill=(34, 139, 34), outline=(0, 100, 0))
    
    # 添加文字
    try:
        font = ImageFont.truetype("arial.ttf", 24)
    except:
        font = ImageFont.load_default()
    
    # 花名
    text_width = draw.textlength(flower_name, font=font)
    draw.text(((width - text_width) // 2, height - 50), flower_name, 
              fill=color_scheme['text'], font=font)
    
    img.save(output_path)
    print(f"创建美观图片: {output_path}")

def main():
    """为所有鲜花创建美观图片"""
    
    # 颜色方案
    color_schemes = {
        '红玫瑰': {
            'bg': (255, 240, 245),
            'bg_end': (255, 228, 235),
            'petals': (220, 20, 60),
            'center': (139, 0, 0),
            'outline': (178, 34, 34),
            'text': (139, 0, 0)
        },
        '粉玫瑰': {
            'bg': (255, 240, 245),
            'bg_end': (255, 228, 235),
            'petals': (255, 182, 193),
            'center': (255, 105, 180),
            'outline': (219, 112, 147),
            'text': (199, 21, 133)
        },
        '白玫瑰': {
            'bg': (248, 248, 255),
            'bg_end': (240, 248, 255),
            'petals': (255, 255, 255),
            'center': (255, 250, 240),
            'outline': (211, 211, 211),
            'text': (105, 105, 105)
        },
        '康乃馨': {
            'bg': (255, 248, 220),
            'bg_end': (255, 239, 213),
            'petals': (255, 160, 122),
            'center': (255, 140, 0),
            'outline': (255, 99, 71),
            'text': (255, 69, 0)
        },
        '百合': {
            'bg': (240, 255, 240),
            'bg_end': (245, 255, 250),
            'petals': (255, 255, 255),
            'center': (255, 255, 224),
            'outline': (144, 238, 144),
            'text': (34, 139, 34)
        },
        '向日葵': {
            'bg': (255, 248, 220),
            'bg_end': (255, 250, 205),
            'petals': (255, 215, 0),
            'center': (184, 134, 11),
            'outline': (218, 165, 32),
            'text': (184, 134, 11)
        },
        '郁金香': {
            'bg': (240, 248, 255),
            'bg_end': (230, 230, 250),
            'petals': (186, 85, 211),
            'center': (147, 112, 219),
            'outline': (138, 43, 226),
            'text': (75, 0, 130)
        },
        '满天星': {
            'bg': (248, 248, 255),
            'bg_end': (245, 245, 245),
            'petals': (255, 255, 255),
            'center': (255, 255, 255),
            'outline': (192, 192, 192),
            'text': (105, 105, 105)
        }
    }
    
    flowers = Flower.objects.all()
    
    for flower in flowers:
        # 确定颜色方案
        scheme_key = '满天星'  # 默认
        for key in color_schemes.keys():
            if key in flower.name:
                scheme_key = key
                break
        
        # 创建图片
        filename = f"{flower.name.replace(' ', '_').replace('花束', '')}.jpg"
        output_path = f"../frontend/images/flowers/{filename}"
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        create_flower_image(flower.name, color_schemes[scheme_key], output_path)
        
        # 更新数据库
        image_url = f"/images/flowers/{filename}"
        flower_image, created = FlowerImage.objects.get_or_create(
            flower=flower,
            is_main=True,
            defaults={
                'image_url': image_url,
                'sort_order': 0
            }
        )
        
        if not created:
            flower_image.image_url = image_url
            flower_image.save()
    
    print("所有鲜花图片创建完成！")

if __name__ == "__main__":
    main()